package com.ruoyi.access.util;

import java.io.*;
import java.security.*;
import java.security.spec.*;
import java.util.Base64;

public class KeyPairUtil {

    /**
     * 生成 RSA 密钥对
     */
    public static KeyPair generateRSAKeyPair(int keySize) throws Exception {
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(keySize);
        return keyGen.generateKeyPair();
    }

    /**
     * 将公钥保存到文件
     */
    public static void savePublicKey(PublicKey publicKey, String filePath) throws IOException {
        byte[] encoded = publicKey.getEncoded();
        String base64 = Base64.getEncoder().encodeToString(encoded);
        try (FileWriter fw = new FileWriter(filePath)) {
            fw.write(base64);
        }
    }

    /**
     * 将私钥保存到文件
     */
    public static void savePrivateKey(PrivateKey privateKey, String filePath) throws IOException {
        byte[] encoded = privateKey.getEncoded();
        String base64 = Base64.getEncoder().encodeToString(encoded);
        try (FileWriter fw = new FileWriter(filePath)) {
            fw.write(base64);
        }
    }

    /**
     * 从文件加载公钥
     */
    public static PublicKey loadPublicKey(String filePath) throws Exception {
        String keyStr = new String(java.nio.file.Files.readAllBytes(new File(filePath).toPath()));
        byte[] decoded = Base64.getDecoder().decode(keyStr);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(decoded);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePublic(keySpec);
    }

    /**
     * 从文件加载私钥
     */
    public static PrivateKey loadPrivateKey(String filePath) throws Exception {
        String keyStr = new String(java.nio.file.Files.readAllBytes(new File(filePath).toPath()));
        byte[] decoded = Base64.getDecoder().decode(keyStr);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decoded);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePrivate(keySpec);
    }

    public static void main(String[] args) throws Exception {
         KeyPair keyPair = generateRSAKeyPair(2048);

         System.out.println("生成的私钥为:"+keyPair.getPrivate().toString());
         System.out.println("生成的公钥为:"+keyPair.getPublic().toString());

         savePrivateKey(keyPair.getPrivate(),"D:/Workspace/Master_work/code/Did_accessControl/privateKey.pem");
         savePublicKey(keyPair.getPublic(),"D:/Workspace/Master_work/code/Did_accessControl/publicKey.pem");

         String publicKey = loadPublicKey("D:/Workspace/Master_work/code/Did_accessControl/publicKey.pem").toString();
         String privateKey = loadPrivateKey("D:/Workspace/Master_work/code/Did_accessControl/privateKey.pem").toString();

        System.out.println("生成的私钥为:"+privateKey.toString());
        System.out.println("生成的公钥为:"+publicKey.toString());

    }

}
